package com.gitee.hermer.engine.jars.dependent.logging.layouts;

import java.util.Properties;

import com.gitee.hermer.boot.jee.commons.collection.StringCache;
import com.gitee.hermer.boot.jee.commons.reflect.ClassUtils;
import com.gitee.hermer.boot.jee.commons.reflect.ReflectUtils;
import com.gitee.hermer.boot.jee.commons.utils.PropertiesUtils;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class SampleModelClassicConverter extends ClassicConverter{

	private static String defaultModel;

	static{
		try{
			Properties properties = PropertiesUtils.loadProperties(EngineConstant.ENGINE_CONFIG_PROPERTIES_FILE_NAME);
			if(properties != null && !properties.isEmpty()){
				defaultModel = new StringCache(PropertiesUtils.getString(properties, EngineConstant.PROPERTIES_VALUE_KEY_DSM_APP_NAME)).append(EngineConstant.STR_SPLIT)
						.append(PropertiesUtils.getString(properties, EngineConstant.PROPERTIES_VALUE_KEY_DSM_APP_VERSION)).toString();
			}
		}catch (Exception e) {
		}
	}
	
	public static String getModelAppInfo(){
		if(EngineConstant.CLASS_ENGINE_APP_CLASS_LOADER != null && ClassUtils.isAssignable(EngineConstant.CLASS_ENGINE_APP_CLASS_LOADER, 
				Thread.currentThread().getContextClassLoader().getClass())){
			try{
				String appName = (String) ReflectUtils.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{}, EngineConstant.CLASS_ENGINE_APP_CLASS_LOADER.getDeclaredMethod(
						EngineConstant.ANNOTATE_FIELD_NAME_APP_NAME));
				String appVersion = (String) ReflectUtils.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{}, EngineConstant.CLASS_ENGINE_APP_CLASS_LOADER.getDeclaredMethod(
						EngineConstant.ANNOTATE_FIELD_NAME_APP_VERSION));
				return new StringCache(appName).append(EngineConstant.STR_SPLIT).append(appVersion).toString();
			}catch (Throwable e) {
				EngineConstant.LOGGER.error(e.getMessage(),e);
			}
		}
		return null;
	}

	@Override
	public String convert(ILoggingEvent arg0) {
		return StringUtils.defaultIfEmpty(getModelAppInfo(), StringUtils.defaultIfEmpty(defaultModel, "self"));
	}

}
